<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/7/25
 * Time: 15:41
 */

namespace app\api\model;


use app\api\controller\KbxToken;
use think\Model;
use think\Config;
use app\admin\controller\Membertype;

class Poi extends Model
{

    public function details($t='',$openid){
        $shu=[];
        $tui1='';
        if ($t!=''){
            $id=$t;
            $member=model('Member')
                ->where('program_openid',$openid)
                ->find();

            $Membertype = new Membertype();
            $discoun_per_arr = $Membertype->get_discoun_per($member['member_id']);//获取折扣集

            $d=  $this->where('id',$id)
                ->field('name,id,groupid,eng_name,introduce,eng_introduce,score,description,ticket,open_time,lat,lng,thumb,groupid,address,total_score,total_comment_num,map_thumb_img,use_time,mobile')
                ->find();

            if($d['ticket']!=='免费'){
                $d['ticket'] = '';
            }

            //增加城市name
            $city = db("city")->where("id",$d['groupid'])->field("name")->find();
            $d['city_name'] = $city['name'];

            $images=!empty($d['thumb'])?explode(',',$d['thumb']):'';
            if ($images!=''){
                $d['thumb']= array_filter($images);
            }else{
                $d['thumb']= '';
            }
            $d['tuijian']= [];
            $tui=model('Goods')
                ->where('FIND_IN_SET('.$d['id'].',goods_location)')
                ->where('relation_type',2)
                ->where('goods_status',1)
                ->field('goods_id,goods_name,classify_id,goods_image,goods_englishname,starttime,endtime')
                ->paginate(6);
            foreach ($tui as $g=>$t){
                $zuizao='';
                $qujian1='';
                $price=[];
                $specs1=db('Specs')->alias('s')
                    ->where('s.goods_id',$t['goods_id'])
                    ->where('s.specs_status','1')
                    ->join('Person p','s.specs_id=p.specs_id')
                    ->where('p.person_status','1')
                    ->field('p.person_price')
                    ->select();
                if (!empty($specs1)){
                    foreach ($specs1 as $k=>$v){
                        $price[]=$v['person_price'];
                    }
                    $max1= max($price);
                    $min1= min($price);

                    $discoun_per = isset($discoun_per_arr[$t['classify_id']]) ? $discoun_per_arr[$t['classify_id']] : 1;//该类型商品的折扣率

                    if (!empty($discoun_per)){
                        $qujian1=  ceil(($min1*$discoun_per)).'~'.ceil(($max1*$discoun_per));
                        if ($max1==$min1){
                            $qujian1=ceil(($min1*$discoun_per));
                        }
                    }else{
                        $qujian1=  "$min1~$max1";
                        if ($max1==$min1){
                            $qujian1=ceil(($min1*$discoun_per));
                        }
                    }

                    $image=!empty($t['goods_image'])?explode(',',$t['goods_image']):'';
                    if ($image!=''){
                        $image= $image['1'];
                    }else{
                        $image= '';
                    }

                    if (time()>$t['starttime'] && time()<$t['endtime'] ){
                        $zuizao='今天';
                    }else if(time()<$t['starttime']){
                        $zuizao=date('m-d',$t['starttime']);
                    }else{
                        $zuizao='未知';
                    }

                    $tui1[]=[
                        'goods_id'=>$t['goods_id'],
                        'name'=>$t['goods_name'],
                        'jiage'=>$qujian1,
                        'image'=>$image,
                        'goods_englishname'=>$t['goods_englishname'],
                        'zuizao'=>$zuizao
                    ];
                    $d['tuijian']=$tui1;
                }
            }
            $d['commentList'] = [];
            $d['nearbySpotList'] = [];
            //评论评分
            $comment_where['poi_id'] = $id;
            $d['comment_score'] = $d['total_comment_num']>0?ceil($d['total_score']*100/$d['total_comment_num'])/100:0;
            $limit = 5;
            //评论列表
            $comment_where['is_show'] = 1;
            $commentList = db("poi_comment pc")
                ->field('pc.comment_id,pc.poi_id,
                    pc.content,pc.create_at,pc.content_img,pc.score,pc.user_id,
                    pc.is_top,pc.is_good,pc.is_anonymous,
                    m.member_nickname as username,
                    th.filepath as userface')
                ->join("tplay_member m","m.member_id=pc.user_id",'LEFT')
                ->join("tplay_attachment th","th.id=m.thumb",'LEFT')
                ->join("tplay_poi poi","poi.id=pc.poi_id",'LEFT')
                ->where($comment_where)
                ->order('pc.is_top desc,pc.is_good desc,pc.create_at desc')
                ->limit($limit)
                ->select();
            if(!empty($commentList)){
                foreach ($commentList as $key=>$value){
                    if($value['is_anonymous']==1 || empty($value['username'])){
                        $commentList[$key]['username'] = '匿名';
                        $commentList[$key]['userface'] = Config::get('default_userface');
                    }
                    $commentList[$key]['create_at'] = date("Y-m-d H:i:s",$value['create_at']);
                    if(!empty($value['content_img'])){
                        $commentList[$key]['content_img'] = explode(",",$value['content_img']);
                    }else{
                        $commentList[$key]['create_at'] = [];
                    }
                }
                $d['commentList'] = $commentList;
            }
            $nearbySpot = [];
            $spots = db("poi")->field("id,name,eng_name,thumb,total_score,total_comment_num,lat,lng")->where(['deleted'=>0,'typeid'=>1])->select();
            if(!empty($spots)){
                foreach ($spots as $spot_v){
                    $limit = $this->getDistance($d['lat'],$d['lng'],$spot_v['lat'],$spot_v['lng']);
                    if($limit<100000 && $d['id']!=$spot_v['id']){
                        $spot_v['thumb'] = explode(",",$spot_v['thumb']);
                        $spot_v['thumb'] = array_filter($spot_v['thumb']);
                        if(!empty($spot_v['thumb'])){
                            $spot_v['thumb'] = array_shift($spot_v['thumb']);
                        }else{
                            $spot_v['thumb'] = '';
                        }
                        if($spot_v['total_comment_num']>0){
                            $spot_v['comment_score'] = ceil($spot_v['total_score']*100/$spot_v['total_comment_num'])/100;
                        }else{
                            $spot_v['comment_score'] = 0;
                        }

                        $spot_v['distance'] = ceil($limit/10)/100;//保留一位小数 单位KM
                        $nearbySpot[] = $spot_v;
                    }
                }
                $nearbySpot = $this->arraySort($nearbySpot,'distance');
                $d['nearbySpotList'] = $nearbySpot;
            }
            //增加攻略
            $article = db('article a')->field('a.id,a.title,a.description,a.browse,a.fabulous,at.filepath')
                ->join('attachment at','at.id=a.thumb','left')
                ->where(['a.is_show'=>'0','a.status'=>1])
                ->where('find_in_set('.$id.',a.poi_ids)')
                ->order('a.is_top desc,a.sort_num desc')
                ->select();
            $d['article'] = $article;
            $shu=[
                'code'=>0,
                'msg'=>'ok',
                'data'=>$d
            ];
        }else{
            $shu=[
                'code'=>101,
                'msg'=>'erreo',
                'data'=>[]
            ];
        }

        return $shu;
    }

    //计算景点距离
    public function getDistance($lat1, $lng1, $lat2, $lng2){
        $earthRadius = 6367000; //approximate radius of earth in meters
        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }

    //根据距离重新排序
    function arraySort($array,$keys,$sort='asc') {
        $newArr = $valArr = array();
        foreach ($array as $key=>$value) {
            $valArr[$key] = $value[$keys];
        }
        ($sort == 'asc') ?  asort($valArr) : arsort($valArr);
        reset($valArr);
        foreach($valArr as $key=>$value) {
            $newArr[$key] = $array[$key];
        }
        $data = array_values($newArr);
        return $data;
    }

    //获取poi的谷歌图片资源
    public function getGoogleMapImgByPOI($poi=[])
    {
        $kbxToken = new KbxToken();
        $token='Bearer '.$kbxToken->kbxToken();

        $url = 'https://d.kwibon.cn/api/travelDesign/getGoogleMapPoint';
        $data['width'] = 600;
        $data['height'] = 300;
        $data['zoom'] = 13;
        $data['location'] = [
            'lat'=>$poi['lat'],
            'lng'=>$poi['lng'],
        ];
        $list = json_encode($data);
        $res=$kbxToken->post_data($url,$list,$token);
        $res=$kbxToken->object_array($res);

        return $res;
    }

    //根据景点获取附近POI 100公里以内
    public function getNearbyPOI($poiid=0,$distance=100000)
    {
        $poiinfo = db("poi")->find($poiid);
        if(empty($poiinfo)){
            return [];
        }

        $nearbySpot = [];
        $spots = db("poi")->field("id,groupid,name,eng_name,thumb,total_score,total_comment_num,lat,lng")->where(['deleted'=>0,'typeid'=>1])->select();
        if(!empty($spots)) {
            foreach ($spots as $spot_v) {
                $limit = $this->getDistance($poiinfo['lat'], $poiinfo['lng'], $spot_v['lat'], $spot_v['lng']);
                if ($limit < $distance && $poiinfo['id'] != $spot_v['id']) {
                    $spot_v['thumb'] = explode(",", $spot_v['thumb']);
                    $spot_v['thumb'] = array_filter($spot_v['thumb']);
                    if (!empty($spot_v['thumb'])) {
                        $spot_v['thumb'] = array_shift($spot_v['thumb']);
                    } else {
                        $spot_v['thumb'] = '';
                    }
                    if ($spot_v['total_comment_num'] > 0) {
                        $spot_v['comment_score'] = ceil($spot_v['total_score'] * 100 / $spot_v['total_comment_num']) / 100;
                    } else {
                        $spot_v['comment_score'] = 0;
                    }

                    $spot_v['distance'] = ceil($limit / 10) / 100;//保留一位小数 单位KM
                    $nearbySpot[] = $spot_v;
                }
            }
            $nearbySpot = $this->arraySort($nearbySpot, 'distance');
            return $nearbySpot;
        }else{
            return [];
        }
    }
}